﻿using System;
using System.IO;
using FunctionalCLR.Core.Function;
using FunctionalCLR.Shell;

namespace FunctionalCLR.Core {

    /// <summary>
    /// Load existed function libraries.
    /// </summary>
    public class UsingNode : ContextFuncNode {
    
        public UsingNode()
            : base() {
            this.Value = "using";
        }

        public override object Evaluate() {
            if (Children.Count < 0) {
                throw new ArgumentException("using function: using(libraryName);");
            }

            string fileName = GetFileName(Children[0].Value);
            string buff = File.ReadAllText(fileName);
            string[] stmts = buff.Split(';');
            foreach (string stmt in stmts) {
                string s = stmt.Trim();
                if (string.IsNullOrEmpty(stmt)) {
                    continue;
                }

                UserDefinedFunctionParser parser 
                    = new UserDefinedFunctionParser(
                        this.Context.GetParserFactory());
                UserDefinedFunctionNode udf = parser.Parse(s);
                Context.GetFunctionManager().Add(udf.Name, udf);
            }

            return string.Empty;
        }

        public static string GetFileName(string name) {
            if (File.Exists(name + ".fp")) {
                return name + ".fp";
            }
            if (File.Exists(name + ".fpz")) {
                return name + ".fpz";
            }

            string fileName = Utils.FunctionPath.EndsWith("\\") ? Utils.FunctionPath + name + ".fp" : Utils.FunctionPath + name + ".fp";
            if(File.Exists(fileName)) {
                return fileName;
            }

            throw new FileNotFoundException(name);
        }
    }
}
